package com.naizhuai.ui;

import android.annotation.TargetApi;

import com.gyf.barlibrary.ImmersionBar;
import com.naizhuai.MainActivity;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.base.DialogControl;
import com.naizhuai.ui.components.TipDialog;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.entity.management.OperateItemBean;
import com.naizhuai.ui.mianbusiness.setting.ManageCreateQRCodeActivity;
import com.naizhuai.ui.mianbusiness.setting.ManageScanQRCodeActivity;
import com.naizhuai.ui.user.login.LoginActivity;
import com.naizhuai.util.ActivityStackManager;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.PermissionRequest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Paint;
import android.os.Build;

import com.naizhuai.R;
import com.naizhuai.util.PermissionRequest;
import com.naizhuai.util.RxBus;
import com.naizhuai.util.SharedPreferenceUtil;
import com.naizhuai.util.ToastCompat;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.security.cert.TrustAnchor;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscription;


import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;

/**
 * @author：lichenxi
 * @date 2018/1/15 13
 * email：525603977@qq.com
 * Fighting
 */
public abstract class BaseActivity extends AppCompatActivity implements DialogControl {
    private PermissionRequest mPermissionRequest;
    private Unbinder unbind;

    private SharedPreferenceUtil mSharedPreferenceUtil;
    private boolean isVisible;
    private TipDialog waitDialog;
    private TipDialog subWaitDialog;
    private ImmersionBar mImmersionBar;
    private WeakReference<Activity> baseWeak;

    public ImmersionBar getImmersionBar() {
        return mImmersionBar;
    }

    public SharedPreferenceUtil getSp() {
        if (mSharedPreferenceUtil == null) {
            mSharedPreferenceUtil = SharedPreferenceUtil.getInstance(this);
        }
        return mSharedPreferenceUtil;

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        int mode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        unbind = ButterKnife.bind(this);
        if (findViewById(R.id.toolbar) != null) {
            mImmersionBar = ImmersionBar.with(this);
            mImmersionBar.titleBar(R.id.toolbar).keyboardMode(mode).statusBarDarkFont(statusBarFontColor()).init();
        }
        baseWeak = new WeakReference<Activity>(this);
        ActivityStackManager.getInstance().addActivity(baseWeak);
//        SystemBarTintManager tintManager = new SystemBarTintManager(this);
//        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setStatusBarTintResource(getBarColor());//通知栏所需颜色
        isVisible = true;
        //       baseView();
//        initCompanyId();
    }

    private void initCompanyId() {
        if (this instanceof MainActivity || this instanceof LoginActivity || this instanceof SplashActivity || this instanceof ManageScanQRCodeActivity || this instanceof ManageCreateQRCodeActivity)
            return;
        String companyId = getShareValue(CompanyBean.COMPANY_ID_KEY, "");
        if (TextUtils.isEmpty(companyId)) {
            shortToast(getString(R.string.not_in_company));
            finish();
        }
    }

    /**
     * 状态栏的文字颜色是否为暗色
     *
     * @return
     */
    protected boolean statusBarFontColor() {
        return true;
    }

    private void baseView() {
        setShareValue(CompanyBean.COMPANY_NAME_KEY, "东莞耐助智能有限公司");
        setShareValue(CompanyBean.COMPANY_ID_KEY, ConstantsPersonResources.COMPANY_ID_TEST_VALUE);
        setShareValue(CompanyBean.COMPANY_THUMB_URL_KEY, "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2887997545,417602002&fm=27&gp=0.jpg");
        setShareValue(ConstantsPersonResources.SESSION_ID_KEY, ConstantsPersonResources.SESSION_TEST_VALUE);
        setShareValue(PersonUserBean.USER_ID_KEY, ConstantsPersonResources.USER_ID_TEST_VALUE);
        setShareValue(DepartmentBean.DEPARTMENT_ID_KEY, "1");
        NaizhuAILog.e("setShareValue(PersonUserBean.USER_ID_KEY, ConstantsPersonResources.USER_ID_TEST_VALUE);" + setShareValue(PersonUserBean.USER_ID_KEY, ConstantsPersonResources.USER_ID_TEST_VALUE));
    }

    protected int getBarColor() {
        return R.color.colorPrimary;
    }

    protected String getStrExtra(String string) {
        if (getIntent().hasExtra(string)) {
            return getIntent().getStringExtra(string);
        } else {
            return "";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStackManager.getInstance().removeActivity(baseWeak);
        if (mImmersionBar != null)
            mImmersionBar.destroy();
        unbind.unbind();
    }

    public PermissionRequest getPermissionRequest() {
        if (mPermissionRequest == null) {
            mPermissionRequest = new PermissionRequest(this);
        }
        return mPermissionRequest;
    }

    public abstract int getLayoutId();

    protected void setTranslucentStatus() {
        Window window = getWindow();
        // Translucent status bar
        window.setFlags(
                FLAG_TRANSLUCENT_STATUS,
                FLAG_TRANSLUCENT_STATUS);
        // Translucent navigation bar
//        window.setFlags(
//                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
//                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }


    public void startActivityTransition(Intent intent) {
        startActivity(intent);
        overridePendingTransition(R.anim.move_right_in_activity, R.anim.move_left_out_activity);

    }

    protected void longToast(String str) {
        ToastCompat.showToast(this, str, Toast.LENGTH_LONG);
    }

    protected void shortToast(String str) {
        ToastCompat.showToast(this, str, Toast.LENGTH_SHORT);
    }

    //默认使用沉浸 可以重写该方法修改选择
    protected boolean isTintSystemBar() {
        return true;
    }

    protected <T> T getShareValue(String keyword, @NonNull T t) {
        return SharedPreferenceUtil.getInstance(this).getValue(keyword, t);
    }

    protected <T> boolean setShareValue(String keyword, T t) {
        return SharedPreferenceUtil.getInstance(this).saveValue(keyword, t);
    }

    protected void getTextUnderLine(TextView view, String strTxt) {
        view.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        view.getPaint().setAntiAlias(true);//抗锯齿
        view.setText(strTxt);
//        view.setText(Html.fromHtml("<u>"+strTxt+"</u>"));
    }

    protected Context getActivityContext() {
        return this;
    }

    @Override
    public TipDialog showWaitDiaLog() {
        return showWaitDialog(getString(R.string.loading));
    }

    @Override
    public TipDialog showWaitDialog(@NonNull int resid) {
        return showWaitDialog(getString(resid));
    }

    @Override
    public TipDialog showWaitDialog(@NonNull String string) {
        if (isVisible) {
            if (waitDialog == null) {
                waitDialog = new TipDialog.Builder(this)
                        .setIconType(TipDialog.Builder.ICON_LOADING)
                        .setTipText(string)
                        .create();
            }
            if (waitDialog != null) {
                if (waitDialog.isShowing()) {
                    waitDialog.dismiss();
                }
                if (!isFinishing())
                    waitDialog.show();
            }
        }
        return waitDialog;
    }

    public void onBackPressedWithoutDialog() {
         super.onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (isWaitDialogShowing()) {
            DialogUtils.showSureDialog(this, getString(R.string.cancel_submit_request), new View.OnClickListener() {
                @Override
                public void onClick(View dialog) {
                    hideWaitDialog();
                }
            });
        } else {
            onBackPressedWithoutDialog();
        }
    }

    protected boolean isWaitDialogShowing() {
        return subWaitDialog != null && subWaitDialog.isShowing();
    }

    protected boolean isWaitDialogShowing1() {
        return waitDialog != null && waitDialog.isShowing();
    }

    @Override
    public void hideWaitDialog() {
        if (isVisible && waitDialog != null) {
            waitDialog.dismiss();
        }
        if (isVisible && subWaitDialog != null) {
            subWaitDialog.dismiss();
        }
    }

    @Override
    public TipDialog showWaitDiaLog(Subscription subscription) {
        if (isVisible) {
            if (subWaitDialog == null) {
                subWaitDialog = new TipDialog.Builder(this)
                        .setIconType(TipDialog.Builder.ICON_LOADING)
                        .setTipText(getString(R.string.loading))
                        .create();
                subWaitDialog.setSubscription(subscription);
                subWaitDialog.show();
            } else {
                if (subWaitDialog.isShowing()) {
                    if (subWaitDialog.getSubscription() != subscription) {
                        subWaitDialog.dismiss();
                        subWaitDialog.setSubscription(subscription);
                        subWaitDialog.show();
                    }
                } else {
                    subWaitDialog.setSubscription(subscription);
                    subWaitDialog.show();
                }
            }
        }
        return subWaitDialog;
    }
    public boolean isComPanyPower(){
        return !TextUtils.isEmpty(AccountHelper.getComPanyid());
    }
}
